﻿using AutoMapper;
using HZY.Quartz.Entitys;
using Microsoft.Extensions.Configuration;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace HZY.Quartz.Service
{
    /// <summary>
    /// 项目服务
    /// </summary>
    public class ProjectService : IProjectService
    {
        private readonly IDataService _fileDataService;
        private readonly IMapper _mapper;
        private readonly IDataStorageConfigurationService _dataStorageConfigurationService;

        public ProjectService(IConfiguration configuration, IDataService fileDataService, IMapper mapper, IDataStorageConfigurationService dataStorageConfigurationService)
        {
            _fileDataService = fileDataService;
            //初始化 FileData服务
            _fileDataService.Init(dataStorageConfigurationService.GetProjectPathOrKey());
            _mapper = mapper;
            _dataStorageConfigurationService = dataStorageConfigurationService;
        }

        /// <summary>
        /// 查询列表
        /// </summary>
        /// <returns></returns>
        public async Task<IEnumerable<Project>> FindListAsync()
            => await _fileDataService.ReadDataAsync<Project>();

        /// <summary>
        /// 保存
        /// </summary>
        /// <param name="form"></param>
        /// <returns></returns>
        public async Task<Project> SaveAsync(Project form)
        {
            var data = (await this.FindListAsync())?.ToList() ?? new List<Project>();
            var project = data.Find(w => w.Id == form.Id);

            if (project == null)
            {
                form.Id = Guid.NewGuid();
                project = _mapper.Map<Project, Project>(form);
                project.CreateTime = DateTime.Now;
                data.Add(project);
            }
            else
            {
                project = _mapper.Map(form, project);
            }

            await _fileDataService.WriteDataAsync(data);

            return project;
        }

        /// <summary>
        /// 删除数据
        /// </summary>
        /// <returns></returns>
        public async Task<bool> DeleteAsync(Guid id)
        {
            var data = (await this.FindListAsync())?.ToList() ?? new List<Project>();
            var project = data.Find(w => w.Id == id);
            if (project == null) return true;

            data.RemoveAt(data.IndexOf(project));

            await _fileDataService.WriteDataAsync(data);

            return true;
        }

        /// <summary>
        /// 根据Id 查询 任务
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<Project> FindByIdAsync(Guid id)
        {
            var data = (await this.FindListAsync())?.ToList() ?? new List<Project>();
            return data.Find(w => w.Id == id) ?? new Project();
        }




    }
}
